<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="仓库" prop="ordersId">
        <treeselect v-model="queryParams.warehouseId" :options="warehouseOptions" :show-count="true" placeholder="请选择仓库"
          style="width: 210px" />
      </el-form-item>
      <el-form-item label="盘点日期" prop="stocktakeDate">
        <el-date-picker clearable v-model="queryParams.stocktakeDate" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择盘点日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="盘点人" prop="checkedBy">
        <el-input v-model="queryParams.checkedBy" placeholder="请输入盘点人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="盘点状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择盘点状态" clearable>
          <el-option v-for="dict in dict.type.inventory_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['depot:stocktakes:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleStocktake"
          v-hasPermi="['depot:stocktakes:edit']">盘点</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDelete(row = null)" v-hasPermi="['depot:stocktakes:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['depot:stocktakes:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stocktakesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="盘点任务唯一标识" align="center" prop="stocktakeId" /> -->
      <el-table-column label="盘点单号" align="center" prop="stocktakeNumber" />
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="盘点日期" align="center" prop="stocktakeDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.stocktakeDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="盘点人" align="center" prop="checkedBy" />
      <el-table-column label="盘点状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inventory_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="notes" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- 盘点按钮：仅在状态为1或2时显示 -->
          <el-button v-if="scope.row.status === 1 || scope.row.status === 2" size="mini" type="text" icon="el-icon-edit"
            @click="handleStocktake(scope.row)" v-hasPermi="['depot:stocktakes:edit']">
            盘点
          </el-button>
          <!-- 删除按钮：仅在状态为1时显示 -->
          <el-button v-if="scope.row.status === 1" size="mini" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)" v-hasPermi="['depot:stocktakes:remove']">
            删除
          </el-button>
          <!-- 详情按钮：仅在状态为3时显示 -->
          <el-button v-if="scope.row.status === 3" size="mini" type="text" icon="el-icon-view"
            @click="handleDetail(scope.row)" v-hasPermi="['depot:stocktakes:query']">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />


    <!-- 添加或盘点任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="5">
            <el-form-item label="仓库" prop="warehouseId">
              <treeselect v-model="form.warehouseId" :options="warehouseOptions" :show-count="true" placeholder="请选择仓库"
                style="width: 210px" :disabled="isStocktake" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="盘点单号" prop="stocktakeNumber">
              <el-input v-model="form.stocktakeNumber" :disabled="true" placeholder="自动生成" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注信息" prop="notes">
          <el-input v-model="form.notes" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>

      <!-- 分隔线 -->
      <el-divider content-position="center">产品信息</el-divider>

      <!-- 产品信息区域 -->
      <div style="margin-top: 10px;">
        <!-- 隐藏添加和删除按钮在盘点模式下 -->
        <div v-if="!isStocktake" style="display: flex; margin-bottom: 10px;">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addProduct">
            添加
          </el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteSelectedProducts"
            style="margin-left: 10px;" :disabled="productTableSelectedIds.length === 0">
            删除
          </el-button>
        </div>

        <!-- 产品信息表格 -->
        <el-table ref="productTable" :data="productList" style="width: 100%;"
          @selection-change="handleProductSelectionChange" row-key="productId"> <!-- 使用唯一标识符作为 row-key -->
          <el-table-column type="selection" min-width="55"></el-table-column>
          <el-table-column prop="productName" label="产品名称" min-width="150"></el-table-column>
          <el-table-column prop="sku" label="产品SKU" min-width="150"></el-table-column>
          <el-table-column prop="actualQuantity" label="库存数量" min-width="100"></el-table-column>
          <pre>{{ productList }}</pre>

          <!-- 新增“盘点数量”列 -->
          <el-table-column label="盘点数量" min-width="100">
            <template slot-scope="scope">
              <el-input v-model.number="scope.row.countQuantity" :disabled="!isStocktake || scope.row.isCounted"
                min="0">
              </el-input>
            </template>
          </el-table-column>

          <!-- 差异列 -->
          <el-table-column label="差异" min-width="100">
            <template slot-scope="scope">
              <span :style="getDifferenceStyle(scope.row.difference)">
                <span
                  v-if="scope.row.difference === null || scope.row.difference === undefined || scope.row.difference === 0">-</span>
                <span v-else>
                  {{ scope.row.difference > 0 ? '+' : '' }}{{ scope.row.difference }}
                </span>
              </span>
            </template>
          </el-table-column>

          <el-table-column label="是否参与盘点" min-width="100" v-if="isStocktake">
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.participateInStocktake" :disabled="scope.row.isCounted"> </el-checkbox>
            </template>
          </el-table-column>


          <!-- 新增“备注”列 -->
          <el-table-column label="备注" min-width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" clearable></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 弹窗底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>

    <!-- 选择产品弹窗 -->
    <el-dialog :title="selectProductTitle" :visible.sync="selectProductOpen" width="50%" append-to-body>
      <el-form :model="selectProductQueryParams" ref="selectProductQueryForm" size="small" :inline="true"
        label-width="80px">
        <el-form-item label="产品sku" prop="purchaseOrderNo">
          <el-input v-model="selectProductQueryParams.sku" placeholder="请输入产品sku" clearable
            @keyup.enter.native="handleSelectProductQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSelectProductQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetSelectProductQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table ref="selectProductTable" v-loading="selectProductLoading" :data="selectProductList"
        @selection-change="handleSelectProductSelectionChange" row-key="productId">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="产品sku" align="center" prop="sku" />
        <el-table-column label="仓库" align="center" prop="warehouseName" />
        <el-table-column label="库存数量" align="center" prop="actualQuantity" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-check" @click="selectProduct(scope.row)">
              {{ selectedProductIds.includes(scope.row.productId) ? '已选择' : '选择' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="selectProductTotal > 0" :total="selectProductTotal"
        :page.sync="selectProductQueryParams.pageNum" :limit.sync="selectProductQueryParams.pageSize"
        @pagination="getSelectProductList" />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSelectProduct">确定</el-button>
        <el-button @click="cancelSelectProduct">取消</el-button>
      </div>
    </el-dialog>


    <!-- 详情弹窗 -->
    <el-dialog :title="detailTitle" :visible.sync="detailOpen" width="80%" append-to-body>
      <el-form :model="detailForm" label-width="80px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="仓库" prop="warehouseId">
              <treeselect v-model="detailForm.warehouseId" :options="warehouseOptions" :show-count="true"
                placeholder="请选择仓库" :disabled="true" style="width: 210px" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="盘点单号" prop="stocktakeNumber">
              <span>{{ detailForm.stocktakeNumber }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="盘点日期" prop="stocktakeDate">
              <span>{{ parseTime(detailForm.stocktakeDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="盘点人" prop="checkedBy">
              <span>{{ detailForm.checkedBy }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="盘点状态" prop="status">
              <dict-tag :options="dict.type.inventory_status" :value="detailForm.status" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注信息" prop="notes">
              <span>{{ detailForm.notes }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 分隔线 -->
        <el-divider content-position="center">产品信息</el-divider>

        <!-- 产品信息区域 -->
        <div style="margin-top: 10px;">
          <!-- 产品信息表格 -->
          <el-table :data="detailForm.stocktakeDetails" style="width: 100%;" row-key="productId">
            <el-table-column label="产品名称" prop="productName" min-width="150"></el-table-column>
            <el-table-column label="产品SKU" prop="sku" min-width="150"></el-table-column>
            <!-- <el-table-column label="仓库" prop="warehouseName" min-width="100"></el-table-column> -->
            <el-table-column label="库存数量" prop="systemQuantity" min-width="100"></el-table-column>
            <el-table-column label="盘点数量" min-width="100">
              <template slot-scope="scope">
                <span>{{ scope.row.countedQuantity }}</span>
              </template>
            </el-table-column>
            <el-table-column label="差异" min-width="100">
              <template slot-scope="scope">
                <span :style="getDifferenceStyle(scope.row.difference)">
                  <span
                    v-if="scope.row.difference === null || scope.row.difference === undefined || scope.row.difference === 0">
                    -
                  </span>
                  <span v-else>
                    {{ scope.row.difference > 0 ? '+' : '' }}{{ scope.row.difference }}
                  </span>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="备注" min-width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.notes ? scope.row.notes : '-' }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <!-- 弹窗底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDetail">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listStocktakes, getStocktakes, delStocktakes, addStocktakes, updateStocktakes, listSelectProduct } from "@/api/depot/stocktakes";
import { getSelectPreWarehouseTreeList } from "@/api/procured/plan";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Stocktakes",
  dicts: ['inventory_status'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中数组盘点单号
      stocktakeNumbers: [],
      // 选中数组盘点状态
      stocktakeStatus: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 盘点任务表格数据
      stocktakesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前模式：'add', 'edit', 'stocktake'
      mode: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseId: null,
        stocktakeDate: null,
        checkedBy: null,
        status: null,
      },
      // 表单参数
      form: {
        stocktakeId: null
      },
      // 表单校验
      rules: {
        warehouseId: [
          { required: true, message: "仓库ID不能为空", trigger: "blur" }
        ],
        stocktakeDate: [
          { required: true, message: "盘点日期不能为空", trigger: "blur" }
        ],
      },
      // 仓库列表
      warehouseOptions: [],
      productList: [], // 产品信息列表
      // 选择产品弹窗相关数据
      selectProductOpen: false, // 选择产品弹窗是否显示
      selectProductTitle: "选择产品", // 选择产品弹窗标题
      selectProductQueryParams: {
        pageNum: 1,
        pageSize: 10,
        sku: null
      },
      selectProductLoading: true,
      selectProductList: [],
      selectProductTotal: 0,
      selectedProductIds: [], // 已选择的产品ID列表
      // 临时存储选择的产品
      // tempProductList: [],
      currentPageSelectedIds: [], // 当前页选中的产品ID列表
      // 独立存储第一个表格（productTable）的选中 ID
      productTableSelectedIds: [],
      // 独立存储第二个表格（selectProductTable）的选中 ID
      // selectProductTableSelectedIds: [],
      isPageChanging: false, // 标志位，标识是否正在切换分页
      selectedProductsData: [], // 已选择的产品数据
      // 新增详情弹窗
      detailOpen: false,
      detailForm: {},
      detailTitle: "详情",
      participateInStocktake: false, // 表示是否参与盘点
    };
  },

  created() {
    this.getList();
    this.getPreWarehouse();
  },
  watch: {
    'form.warehouseId'(newVal, oldVal) {
      if (newVal !== oldVal && this.mode !== 'stocktake') {
        this.resetAdd();
      }
    },
    // 监听产品列表中的 countQuantity 变化
    'productList': {
      handler(newProductList) {
        newProductList.forEach(product => {
          if (typeof product.countQuantity !== 'undefined' && product.countQuantity !== null) {
            this.updateDifference(product);
          } else {
            // 如果 countQuantity 为空或未定义，则设置 difference 为 null
            this.$set(product, 'difference', null);
          }
        });
      },
      deep: true, // 深度监听 productList 中的每一项对象
    },
  },
  computed: {
    isStocktake() {
      return this.mode === "stocktake";
    }
  },
  methods: {
    /** 查询盘点任务列表 */
    getList() {
      this.loading = true;
      listStocktakes(this.queryParams).then(response => {
        this.stocktakesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        stocktakeId: null,
        warehouseId: null,
        stocktakeDate: null,
        checkedBy: null,
        status: null,
        notes: null,
        createdAt: null,
        updatedAt: null
      };
      this.resetForm("form");
      this.mode = ""; // 重置模式
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.warehouseId = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.stocktakeId)
      this.stocktakeNumbers = selection.map(item => item.stocktakeNumber)
      this.stocktakeStatus = selection.map(item => item.status)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加盘点任务";
      this.mode = "add";
      this.resetAdd();
    },
    /** 重置添加盘点任务弹窗中相关数据 */
    resetAdd() {
      // 重置选择相关的变量
      this.selectedProductIds = []; // 重置已选择的产品ID列表
      this.selectedProductsData = []; // 重置已选择的产品数据
      this.productList = []; // 重置产品信息列表
      this.productTableSelectedIds = []; // 重置主表格选中ID列表
      this.currentPageSelectedIds = []; // 重置当前页选中ID列表
      this.selectProductTableSelectedIds = []; // 重置选择产品弹窗表格选中ID列表

      // 清空选择产品弹窗表格的选中状态
      if (this.$refs.selectProductTable) {
        this.$refs.selectProductTable.clearSelection();
      }

      // 清空主产品表格的选中状态
      if (this.$refs.productTable) {
        this.$refs.productTable.clearSelection();
      }
    },
    /** 盘点按钮操作 */
    async handleStocktake(row) {
      // 确保 stocktakeId 正确赋值
      const stocktakeId = row && row.stocktakeId ? row.stocktakeId :
        (Array.isArray(this.ids) && this.ids.length === 1 ? this.ids[0] : null);

      const status = row.status ? row.status : this.stocktakeStatus[0];

      if (status == 3) {
        this.$modal.msgWarning("盘点单已完成盘点！");
        return;
      }
      // 确保传递单个 ID
      if (!stocktakeId) {
        this.$modal.msgWarning("请选择一个盘点任务进行盘点！");
        return;
      }
      try {
        this.reset();
        this.open = true;
        this.title = "盘点任务";
        this.mode = "stocktake";
        // 调用 API 获取盘点任务详情
        const response = await getStocktakes(stocktakeId);
        this.form = response.data;

        // 映射 API 返回的数据到 productList
        this.productList = response.data.stocktakeDetails.map(item => ({
          stocktakeDetailId: item.stocktakeDetailId,
          productId: item.productId, // 确保使用 productId
          productName: item.productName || item.sku, // 使用 sku 作为备用
          sku: item.sku,
          warehouseId: item.warehouseId,
          actualQuantity: item.systemQuantity, // 库存数量
          countQuantity: item.countedQuantity, // 盘点数量
          remark: item.notes, // 备注
          difference: null, // 初始化差异
          isCounted: item.isInventoried, // 标记是否已盘点
          version: item.inventoryVersion
        }));
      } catch (error) {
        this.$modal.msgError("获取盘点任务详情失败");
        console.error("获取盘点任务详情失败:", error);
      }
    },

    /** 处理详情按钮操作 */
    async handleDetail(row) {
      try {
        // 调用 API 获取盘点任务详情
        const response = await getStocktakes(row.stocktakeId);
        this.detailForm = response.data;
        this.detailOpen = true;
      } catch (error) {
        this.$modal.msgError("获取盘点任务详情失败");
        console.error("获取盘点任务详情失败:", error);
      }
    },

    /** 关闭详情弹窗 */
    closeDetail() {
      this.detailOpen = false;
      this.detailForm = {};
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const stocktakeId = row.stocktakeId || this.ids
      getStocktakes(stocktakeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改盘点任务";
      });
    },

    /** 提交表单 */
    async submitForm() {
      try {
        const isValid = await this.$refs["form"].validate();
        if (!isValid) {
          return;
        }

        // 根据当前模式处理不同的逻辑
        if (this.mode === "add") {
          // 新增盘点任务
          const payload = {
            ...this.form,
            products: this.productList.map(item => ({
              productName: item.productName,
              sku: item.sku,
              actualQuantity: item.actualQuantity,
              remark: item.remark,
              version: item.version
            }))
          };

          try {
            await addStocktakes(payload);
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          } catch (error) {
            this.$modal.msgError("新增失败");
          }
        } else if (this.mode === "stocktake") {
          // 过滤出 countQuantity 大于0的产品
          // const filteredProducts = this.productList.filter(item => item.countQuantity > 0 && !item.isCounted);
          // 筛选出标记为参与盘点 且 尚未盘点的产品
          const filteredProducts = this.productList.filter(item =>
            item.participateInStocktake === true && // 检查参与标志
            !item.isCounted);                      // 确保尚未盘点

          // 如果没有任何产品需要盘点，提示用户并阻止提交
          if (filteredProducts.length === 0) {
            this.$modal.msgWarning("没有盘点数量有效的产品");
            return;
          }

          // 提示用户仅盘点数量不为0的数据
          this.$modal.confirm("确认提交本次输入的盘点数量吗？（盘点数量为0的产品也将被处理）")
            .then(async () => {
              const payload = {
                ...this.form,
                stocktakeDetails: filteredProducts.map(item => ({
                  stocktakeDetailId: item.stocktakeDetailId,
                  productName: item.productName,
                  sku: item.sku,
                  warehouseId: item.warehouseId,
                  systemQuantity: item.actualQuantity,
                  countedQuantity: item.countQuantity,
                  difference: item.difference,
                  notes: item.remark,
                  inventoryVersion: item.version
                }))
              };
              try {
                // 执行盘点操作
                await updateStocktakes(payload);
                this.$modal.msgSuccess("盘点成功");
                this.open = false;
                this.getList();
              } catch (error) {
                this.$modal.msgError("盘点失败");
                console.error("盘点失败:", error);
              }
            })
            .catch(() => {
              // 用户点击了取消按钮，可以执行其他操作或不做任何事情
            });
        }
      } catch (validationError) {
        console.error("表单验证失败:", validationError);
      }
    },


    /** 删除按钮操作 */
    handleDelete(row) {
      let stocktakeIds = [];
      let stocktakeNumbers = [];
      if (row) {
        if (row.status !== 1) {
          this.$modal.msgWarning("盘点任务已完成或者进行中不能够进行删除！");
          return;
        }
        stocktakeIds = [row.stocktakeId];
        stocktakeNumbers = [row.stocktakeNumber]
      } else {
        // 批量删除
        const selectedTasks = this.stocktakesList.filter(item => this.ids.includes(item.stocktakeId));

        const invalidTasks = selectedTasks.filter(item => item.status !== 1);

        if (invalidTasks.length > 0) {
          this.$modal.msgWarning("包含已完成或者盘点中的盘点任务不能够进行删除！");
          return;
        }
        stocktakeNumbers = this.stocktakeNumbers;
        stocktakeIds = this.ids;
      }

      this.$modal.confirm('是否确认删除盘点任务编号为"' + stocktakeNumbers.join(', ') + '"的数据项？')
        .then(() => {
          return delStocktakes(stocktakeIds);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .catch(() => { /* 用户取消删除操作 */ });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('depot/stocktakes/export', {
        ...this.queryParams
      }, `stocktakes_${new Date().getTime()}.xlsx`)
    },
    /** 查询仓库 */
    getPreWarehouse() {
      getSelectPreWarehouseTreeList().then((response) => {
        this.warehouseOptions = response.data;
      });
    },




    // 添加产品
    async addProduct() {
      if (!this.form.warehouseId) {
        this.$message.warning('请先选择要盘点的仓库！');
        return;
      }
      this.selectProductQueryParams.sku = null;//清空搜索条件
      // this.tempProductList = [];// 重置临时选择的产品列表
      this.selectProductOpen = true;// 打开选择产品弹窗
      try {
        // 等待产品列表加载完成
        await this.getSelectProductList();

      } catch (error) {
        console.error("获取产品列表失败", error);
      }
    },

    /** 确认选择产品 */
    confirmSelectProduct() {
      this.selectProductOpen = false;

      // 获取当前已选择的产品ID集合
      const selectedIdsSet = new Set(this.selectedProductIds);

      // 从 selectedProductsData 中获取所有已选择的产品
      const selectedProducts = this.selectedProductsData.filter(product =>
        selectedIdsSet.has(product.productId)
      );

      // 移除 productList 中不再被选择的产品
      this.productList = this.productList.filter(product => selectedIdsSet.has(product.productId));

      // 找出 selectedProducts 中尚未在 productList 中的产品
      const newProducts = selectedProducts.filter(product =>
        !this.productList.some(existing => existing.productId === product.productId)
      );

      // 将新选择的产品添加到 productList
      this.productList = [...this.productList, ...newProducts];
    },

    selectProduct(row) {

      const table = this.$refs.selectProductTable;
      if (table && typeof table.toggleRowSelection === 'function') {
        table.toggleRowSelection(row);
      } else {
        console.warn("toggleRowSelection 方法不存在或表格未渲染");
      }
    },


    // 取消选择产品时不更新产品列表
    cancelSelectProduct() {
      this.selectProductOpen = false;
      // 清空临时选择的产品列表
      // this.tempProductList = [];
      // 清空当前页的选择状态
      this.currentPageSelectedIds = [];
      // 清空表格的所有选中状态
      if (this.$refs.selectProductTable) {
        this.$refs.selectProductTable.clearSelection();
      }
      // 确保 selectedProductIds 只包含 productList 中的 IDs
      this.selectedProductIds = this.productList.map(item => item.productId);
    },

    /** 处理产品表格中的选择变化 */
    handleProductSelectionChange(selection) {
      this.productTableSelectedIds = selection.map(item => item.productId);
      this.single = this.productTableSelectedIds.length !== 1;
      this.multiple = this.productTableSelectedIds.length < 1;
    },

    /** 删除已选产品 */
    deleteSelectedProducts() {
      const productIdsToDelete = this.productTableSelectedIds;

      if (!productIdsToDelete || productIdsToDelete.length === 0) {
        this.$modal.msgWarning("请选择要删除的产品！");
        return;
      }

      this.$modal.confirm(`是否确认删除产品编号为"${productIdsToDelete.join(', ')}"的产品？`)
        .then(() => {
          // 从 productList 中移除选中的产品
          this.productList = this.productList.filter(item => !productIdsToDelete.includes(item.productId));

          // 从 selectedProductsData 中移除已删除的产品数据
          this.selectedProductsData = this.selectedProductsData.filter(product => !productIdsToDelete.includes(product.productId));


          // 从 selectedProductIds 中移除已删除的 ID
          this.selectedProductIds = this.selectedProductIds.filter(id => !productIdsToDelete.includes(id));

          // 清空当前表格的选择状态
          this.productTableSelectedIds = [];
          this.$refs.productTable.clearSelection();


          // 提示删除成功
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
          // 取消删除操作
        });
    },

    // 获取产品列表
    getSelectProductList() {
      this.selectProductLoading = true;
      this.isPageChanging = true; // 设置标志位，开始分页切换
      // 在查询参数中加入仓库ID
      this.selectProductQueryParams.warehouseId = this.form.warehouseId;

      return listSelectProduct(this.selectProductQueryParams).then(response => {
        // **重新排序：将已选择的产品放在前面**
        const selectedProducts = response.rows.filter(product => this.selectedProductIds.includes(product.productId));
        const unselectedProducts = response.rows.filter(product => !this.selectedProductIds.includes(product.productId));
        response.rows = selectedProducts.concat(unselectedProducts);

        this.selectProductList = response.rows;
        this.selectProductTotal = response.total;
        this.selectProductLoading = false;

        const ids = this.selectedProductIds;
        // 在加载完产品列表后，自动选中已选择的产品
        this.$nextTick(() => {
          this.$refs.selectProductTable.clearSelection();
          const selectedRows = this.selectProductList.filter(item =>
            ids.includes(item.productId)
          );

          selectedRows.forEach(row => {
            if (this.$refs.selectProductTable && typeof this.$refs.selectProductTable.toggleRowSelection === 'function') {
              this.$refs.selectProductTable.toggleRowSelection(row, true);
            }
          });

          // 更新当前页的选择状态
          this.currentPageSelectedIds = selectedRows.map(row => row.productId);
          this.isPageChanging = false; // 重置标志位，分页切换完成
        });
      }).catch(error => {
        console.error("获取选择产品列表失败", error);
        this.selectProductLoading = false;
        this.isPageChanging = false; // 确保在出错时重置标志位
      });
    },


    // 处理选择产品查询
    handleSelectProductQuery() {
      this.selectProductQueryParams.pageNum = 1;
      this.getSelectProductList();
    },

    // 重置选择产品查询表单
    resetSelectProductQuery() {
      this.selectProductQueryParams = { pageNum: 1, pageSize: 10, purchaseOrderNo: null };
      this.handleSelectProductQuery();
    },

    /** 处理选择产品表格中的选择变化 */
    handleSelectProductSelectionChange(selection) {
      if (this.isPageChanging) {
        // 如果正在切换分页，不处理此次事件
        return;
      }
      const newSelectedIds = selection.map(item => item.productId);
      const addedIds = newSelectedIds.filter(id => !this.selectedProductIds.includes(id));
      const removedIds = this.currentPageSelectedIds.filter(id => !newSelectedIds.includes(id));


      // 添加新选择的ID
      this.selectedProductIds = [...this.selectedProductIds, ...addedIds];

      // 移除取消选择的ID
      this.selectedProductIds = this.selectedProductIds.filter(id => !removedIds.includes(id));

      // 更新 selectedProductsData
      const addedProducts = selection.filter(item => addedIds.includes(item.productId));
      const removedProducts = this.selectedProductsData.filter(item => removedIds.includes(item.productId));

      // 添加新选择的产品数据
      this.selectedProductsData = [...this.selectedProductsData, ...addedProducts];

      // 移除取消选择的产品数据
      this.selectedProductsData = this.selectedProductsData.filter(item => !removedIds.includes(item.productId));


      // 更新当前页的选择状态
      this.currentPageSelectedIds = newSelectedIds;
    },
    // 获取差异列的样式
    getDifferenceStyle(difference) {
      if (difference > 0) {
        return { color: 'green', fontWeight: 'bold' }; // 正数，绿色
      } else if (difference < 0) {
        return { color: 'red', fontWeight: 'bold' }; // 负数，红色
      } else {
        return {}; // 差异为0或无效，不设置样式
      }
    },

    // 更新差异列的值
    updateDifference(row) {
      // 计算差异值并更新
      row.difference = row.countQuantity - row.actualQuantity;

      // 计算差异值
      const difference = row.countQuantity - row.actualQuantity;

      // 使用 Vue.set 确保差异是响应式的
      this.$set(row, 'difference', difference);
    }
  }
};
</script>
<style>
.text-green {
  color: green;
}

.text-red {
  color: red;
}
</style>